/*
 * Copyright (c) 2025 Industrial Software Feature Database
 */
package com.comac.ins.bomt.service.impl;

import com.comac.ins.bomt.domain.vo.CodeNameItem;
import com.comac.ins.bomt.service.SectionService;
import com.comac.ins.common.biz.exception.BizException;
import com.comac.ins.common.biz.utils.BizAssertUtil;
import com.comac.ins.common.json.utils.JsonUtils;
import com.comac.ins.isfd.constant.enums.IsfdStructureDefinitionTreeTaskDefaultEnum;
import com.comac.ins.isfd.domain.bo.IsfdModelManagementStructureDefinitionTreeBo;
import com.comac.ins.isfd.domain.vo.IsfdModelManagementStructureDefinitionTreeNodeVo;
import com.comac.ins.isfd.service.IIsfdModelManagementStructureDefinitionTreeService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.text.MessageFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 部段服务
 *
 * @author zhanghongyi
 * @date 2024 /8/27
 * @description SectionServiceImpl
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class SectionServiceImpl implements SectionService {


    private final IIsfdModelManagementStructureDefinitionTreeService isfdModelManagementStructureDefinitionTreeService;


    @Override
    public Map<String, List<String>> getSectionGroupConfig(String aircraftModel,String track) {
        Map<String, List<String>> result = getSectionConfig(aircraftModel,track);
        return result;
    }


    public void upsertSectionGroupConfig(String aircraftModel, String track, List<CodeNameItem> sectionCodeNames) {
        BizAssertUtil.isTrue(sectionCodeNames.stream().map(CodeNameItem::getCode).distinct().toList().size() == sectionCodeNames.size(), "sectionCodeNames code not unique");
        BizAssertUtil.isTrue(sectionCodeNames.stream().map(CodeNameItem::getName).distinct().toList().size() == sectionCodeNames.size(), "sectionCodeNames name not unique");
        List<IsfdModelManagementStructureDefinitionTreeNodeVo> queryTree = isfdModelManagementStructureDefinitionTreeService.queryListTree();
        if(queryTree.stream().noneMatch(item->StringUtils.equals(item.getName(),aircraftModel )||StringUtils.equals(item.getMark(), aircraftModel))){
            IsfdModelManagementStructureDefinitionTreeBo bo = new IsfdModelManagementStructureDefinitionTreeBo();
            bo.setParentId(0L);
            bo.setLevel(1);
            bo.setTaskDefault(IsfdStructureDefinitionTreeTaskDefaultEnum.NOT_DEFAULT.getValue());
            bo.setName(aircraftModel);
            bo.setMark(aircraftModel);
            isfdModelManagementStructureDefinitionTreeService.insertByBo(bo);
            queryTree = isfdModelManagementStructureDefinitionTreeService.queryListTree();
        }
        IsfdModelManagementStructureDefinitionTreeNodeVo aircraftNode = queryTree.stream().filter(item -> StringUtils.equals(item.getName(),aircraftModel )||StringUtils.equals(item.getMark(), aircraftModel)).findFirst().orElse(null);
        BizAssertUtil.notNull(aircraftNode,"未找到机型"+aircraftModel+"对应的构型定义");
        if(aircraftNode.getChildren().stream().noneMatch(item->StringUtils.equals(item.getMark(),track)||StringUtils.equals(item.getName(),track))){
            IsfdModelManagementStructureDefinitionTreeBo bo = new IsfdModelManagementStructureDefinitionTreeBo();
            bo.setParentId(aircraftNode.getId());
            bo.setLevel(2);
            bo.setTaskDefault(IsfdStructureDefinitionTreeTaskDefaultEnum.NOT_DEFAULT.getValue());
            bo.setName(track);
            bo.setMark(track);
            isfdModelManagementStructureDefinitionTreeService.insertByBo(bo);
            queryTree = isfdModelManagementStructureDefinitionTreeService.queryListTree();
            aircraftNode = queryTree.stream().filter(item -> StringUtils.equals(item.getName(),aircraftModel )||StringUtils.equals(item.getMark(), aircraftModel)).findFirst().orElse(null);
            BizAssertUtil.notNull(aircraftNode,"未找到机型"+aircraftModel+"对应的构型定义");
        }
        IsfdModelManagementStructureDefinitionTreeNodeVo trackNode = aircraftNode.getChildren().stream().filter(item -> StringUtils.equals(item.getMark(),track)||StringUtils.equals(item.getName(),track)).findFirst().orElse(null);
        BizAssertUtil.notNull(trackNode,"未找到机型:"+aircraftModel+"的批次号:"+track+"对应的构型定义");
        for(CodeNameItem sectionCodeNameItem:sectionCodeNames){
            if(trackNode.getChildren().stream().noneMatch(item->StringUtils.equals(item.getMark(),sectionCodeNameItem.getCode()))){
                IsfdModelManagementStructureDefinitionTreeBo bo = new IsfdModelManagementStructureDefinitionTreeBo();
                bo.setParentId(trackNode.getId());
                bo.setLevel(3);
                bo.setTaskDefault(IsfdStructureDefinitionTreeTaskDefaultEnum.NOT_DEFAULT.getValue());
                bo.setName(sectionCodeNameItem.getName());
                bo.setMark(sectionCodeNameItem.getCode());
                isfdModelManagementStructureDefinitionTreeService.insertByBo(bo);
            }
        }
    }

    /**
     * 获取逆部段分组配置
     */
    @Override
    public Map<String, String> getReverseSectionGroupConfig(String aircraftModel, String track) {
        Map<String, List<String>> sectionGroupConfig = getSectionGroupConfig(aircraftModel,track);
        Map<String, String> reverseGroupConfig = new HashMap<>(10);
        for (Map.Entry<String, List<String>> entry : sectionGroupConfig.entrySet()) {
            for (String section : entry.getValue()) {
                reverseGroupConfig.put(section, entry.getKey());
            }
        }
        return reverseGroupConfig;
    }
    private Map<String, List<String>> getSectionConfig(String aircraftModel,String track) {

        List<IsfdModelManagementStructureDefinitionTreeNodeVo> queryResult = isfdModelManagementStructureDefinitionTreeService.queryListTree();
        log.info("section group query result:{}", JsonUtils.toJsonString(queryResult));
        if (queryResult.stream().anyMatch(item->StringUtils.equals(item.getName(),aircraftModel)||StringUtils.equals(item.getMark(),aircraftModel))) {
            IsfdModelManagementStructureDefinitionTreeNodeVo aircraftNode = queryResult.stream().filter(item -> StringUtils.equals(item.getName(), aircraftModel) || StringUtils.equals(item.getMark(), aircraftModel)).findFirst().orElse(null);
            BizAssertUtil.notNull(aircraftNode, "请前往有限元模型组装-构型定义机型:" + aircraftModel + "对应的构型定义");
            List<IsfdModelManagementStructureDefinitionTreeNodeVo> config = aircraftNode.getChildren();
            IsfdModelManagementStructureDefinitionTreeNodeVo sectionConfig = config.stream()
                .filter(item-> {
                        if (StringUtils.isBlank(track)) {
                            return item.getTaskDefault() == 1;
                        } else {
                            return StringUtils.equals(track,item.getMark())||StringUtils.equals(track,item.getName());
                        }
                    }
                )
                .max(Comparator.comparingLong(IsfdModelManagementStructureDefinitionTreeNodeVo::getId))
                .orElse(null);
            BizAssertUtil.notNull(sectionConfig, MessageFormat.format("请前往有限元模型组装-构型定义，配置机型{0}对应的{1}批次", aircraftModel,track == null?"默认批次":track));
            BizAssertUtil.notEmpty(sectionConfig.getChildren(), MessageFormat.format("请前往有限元模型组装-构型定义，配置机型{0}默认批次{1}的部段定义", aircraftModel, sectionConfig.getName()));
            Map<String, List<String>> result = sectionConfig.getChildren().stream().collect(Collectors.toMap(IsfdModelManagementStructureDefinitionTreeNodeVo::getMark, item -> {
                String[] valueTokens = StringUtils.split(item.getName(), ",");
                if (valueTokens != null && valueTokens.length > 0) {
                    return Arrays.asList(valueTokens);
                } else {
                    return new ArrayList<>();
                }
            }, (a, b) -> a));
            BizAssertUtil.notEmpty(result,"group config is empty");
            for(Map.Entry<String,List<String>> entry:result.entrySet()){
                BizAssertUtil.notNull(entry.getKey(),"isfd query result is invalid");
                if(CollectionUtils.isEmpty(entry.getValue())){
                    log.warn("isfd query result is invalid:{}", JsonUtils.toJsonString(queryResult));
                }
            }
            log.info("final group:size:{},config:{}", result.size(), JsonUtils.toJsonString(result));
            return result;
        } else {
            throw new BizException("请前往有限元模型组装-构型定义机型:" + aircraftModel + "对应的构型定义");
        }
    }
}
